#    Tichy
#
#    copyright 2008 Guillaume Chereau (charlie137@gmail.com)
#
#    This file is part of Tichy.
#
#    Tichy is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Tichy is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Tichy.  If not, see <http://www.gnu.org/licenses/>.


from attribute import Attribute


class Property(object):

    def __init__(self, func, *args):
        assert all(isinstance(x, Attribute) for x in args)
        self.args = [x.name for x in args]
        self.func = func
        self.attr_name = '_property__%s' % self.func.__name__

    def __get__(self, obj, type=None):
        if not hasattr(obj, self.attr_name):
            self._init(obj)
        return getattr(obj, self.attr_name)

    def _init(self, obj):
        value = self.func(obj)
        setattr(obj, self.attr_name, value)
        # TODO: we should ensure that we call this slot before normal
        #       slots !
        obj.connect('modified', self._recompute)

    def _recompute(self, obj):
        value = self.func(obj)
        getattr(obj, self.attr_name).value = value.value


def property(func):
    return Property(func)
